package com.cloudcode.common.utils;

import cn.hutool.json.JSONUtil;
import com.cloudcode.common.constant.GlobalConstants;
import com.cloudcode.common.entity.SysUserDTO;
import com.cloudcode.common.entity.UserDetail;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Optional;

/**
 * @author yunst
 * @date 2023/6/5
 */
@Slf4j
public class SysUserUtils {
    /**
     * 获取当前登录用户.
     *
     * @return Optional 包裹的 sysUser，sysUser 有获取不到的情况.
     */
    public static Optional<UserDetail> getCurrentUser() {
        try {
            ServletRequestAttributes requestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest request = requestAttributes.getRequest();
            String userInfo = request.getHeader(GlobalConstants.USER_HEADER);
            log.debug("userinfo:{} ", userInfo);
            return Optional.ofNullable(userInfo).map(user -> JSONUtil.toBean(userInfo, UserDetail.class));
        } catch (IllegalStateException e) {
            log.error("获取当前用户失败.", e);
        }
        return Optional.empty();
    }
}
